<!--
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-11-21 17:13:52
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-08-11 14:20:30
 * @Description:
 *
-->

<template>
  <MyContainer class="container">
    <MyHeader class="header">
      <el-input
        v-model="searchKey"
        style="width: 200px; margin-right: 20px"
        size="medium"
        class="input"
        placeholder="请输入关键字进行过滤"
        clearable
        @clear="clearClick"
        @keyup.enter.native="queryClick"
      />
      <el-button
        size="medium"
        type="primary"
        @click="queryClick"
      >查询</el-button>
      <el-button
        size="medium"
        style="margin-left: 30px"
        type="primary"
        @click="advancedClick"
      >高级搜索</el-button>
      <el-button
        size="medium"
        style="margin-left: auto"
        type="primary"
        icon="el-icon-refresh"
        :loading="syncLoading"
        @click="syncClick"
      >同步</el-button>
      <el-button
        size="medium"
        type="primary"
        icon="el-icon-plus"
        @click="createClick"
      >创建资源规格</el-button>
    </MyHeader>
    <div class="main">
      <div v-for="(item, index) in list" :key="index" class="list-item">
        <el-row class="top" type="flex" align="middle">
          <div class="name">{{ item.name }}</div>
          <el-button
            type="primary"
            size="mini"
            style="margin-left: auto; height: 22px; padding: 0 10px"
            :disabled="!isRowCloudPublic(item)"
            @click="editClick(item)"
          >编辑</el-button>
          <el-popover
            :ref="`popover-delete-${index}`"
            placement="top"
            width="300"
            style="margin-left: 10px"
          >
            <p>是否确认删除该资源规格？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="deleteCancel(index)"
              >取消</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="deleteClick(item, index)"
              >确定</el-button>
            </div>
            <el-button
              slot="reference"
              type="danger"
              style="height: 22px; padding: 0 10px"
              size="mini"
            >删除</el-button>
          </el-popover>
        </el-row>
        <div class="divider"></div>
        <div class="block">
          <div class="title">基本信息</div>
          <div class="row">
            <div class="row-item">
              <div class="key">云服务商</div>
              <div class="val">{{ item.cloudProvider }}</div>
            </div>
            <div class="row-item">
              <div class="key">云账号名称</div>
              <div class="val">{{ item.cloudAccountName }}</div>
            </div>
            <div class="row-item">
              <div class="key">区域</div>
              <div class="val">{{ item.region || "-" }}</div>
            </div>
            <div class="row-item">
              <div class="key">公有</div>
              <div class="val">{{ item.publicOwned }}</div>
            </div>
            <div class="row-item">
              <div class="key">创建人</div>
              <div class="val">{{ item.createBy }}</div>
            </div>
            <div class="row-item">
              <div class="key">创建时间</div>
              <div class="val">{{ item.createDate }}</div>
            </div>
          </div>
        </div>
        <div class="block">
          <div class="title">规格信息</div>
          <div class="row">
            <div class="row-item">
              <div class="key">CPU架构</div>
              <div class="val">{{ item.cpuArch || "-" }}</div>
            </div>
            <div class="row-item">
              <div class="key">vCPU数量</div>
              <div class="val">{{ item.cpuCount }}</div>
            </div>
            <div class="row-item">
              <div class="key">内存（GiB）</div>
              <div class="val">{{ item.memSize }}</div>
            </div>
            <div class="row-item">
              <div class="key">根磁盘（GiB）</div>
              <div class="val">{{ item.rootDiskSize || "-" }}</div>
            </div>
            <div class="row-item">
              <div class="key">GPU</div>
              <div class="val">{{ item.gpu || "-" }}</div>
            </div>
            <div class="row-item">
              <div class="key">GPU显存</div>
              <div class="val">{{ item.gpuMemSize || "-" }}</div>
            </div>
          </div>
        </div>
      </div>
      <el-row type="flex" justify="end" style="margin-top: 30px">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="pageSize"
          :current-page.sync="pageNum"
          :total="totalCount"
          @current-change="changePage"
          @size-change="sizeChange"
        />
      </el-row>
    </div>
    <!-- 创建  -->
    <CreateDialog
      v-if="showCreateDialog"
      :show.sync="showCreateDialog"
      @success="createSuccessCallback"
    />
    <!-- 编辑 -->
    <UpdateDialog
      v-if="showUpdateDialog"
      :show.sync="showUpdateDialog"
      :info="updateInfo"
      @success="updateSuccessCallback"
    />
    <AdvancedSearchDialog
      :show.sync="showAdvancedDialog"
      :options="advancedSearchOptions"
      :default-keys="['区域', 'vCPU数量', '内存（GiB）']"
      @confirm="advancedConfirmCallback"
    />
  </MyContainer>
</template>

<script>
import pagePermissionMixin from '@/views/mixin/pagePermission.js'
import pageQueryMixin from '@/views/mixin/pageQuery.js'
import MyContainer from '@/components/Layout/MyContainer.vue'
import MyHeader from '@/components/Layout/MyHeader.vue'
import CreateDialog from './CreateDialog.vue'
import UpdateDialog from './UpdateDialog.vue'
import AdvancedSearchDialog from '@/components/AdvancedSearchDialog'
import {
  syncInstanceType,
  getInstanceTypeList,
  deleteInstanceType
} from '@/api/cn-resource'
import { isCloudPublic } from '@/utils/constant'

export default {
  name: 'InstanceTypeMgmt',
  components: {
    MyContainer,
    MyHeader,
    CreateDialog,
    UpdateDialog,
    AdvancedSearchDialog
  },
  mixins: [pagePermissionMixin, pageQueryMixin],
  data() {
    return {
      criteria: {},
      selection: [],
      btnLoadingBatchDel: false, // 批量删除loading
      syncLoading: false, // 同步loading
      showCreateDialog: false,
      showUpdateDialog: false,
      updateInfo: {},
      showAdvancedDialog: false,
      advancedSearchOptions: [
        {
          label: '资源规格名称',
          value: '资源规格名称'
        },
        {
          label: '云服务商',
          value: '云服务商'
        },
        {
          label: '云账号名称',
          value: '云账号名称'
        },
        {
          label: '区域',
          value: '区域'
        },
        {
          label: 'vCPU数量',
          value: 'vCPU数量'
        },
        {
          label: '内存（GiB）',
          value: '内存（GiB）'
        },
        {
          label: '公有',
          value: '公有'
        },
        {
          label: '创建人',
          value: '创建人'
        }
      ]
    }
  },
  created() {},
  methods: {
    /**
     * @description: 高级搜索回调
     * @param {*} val
     * @return {*}
     */
    advancedConfirmCallback(val) {
      this.criteria = val
      this.searchKey = ''
      this.pageNum = 1
      this.getList() // 请求数据
    },
    /**
     * @description:
     * @return {*}
     */
    advancedClick() {
      this.showAdvancedDialog = true
    },
    /**
     * @description: 更新 回调
     * @return {*}
     */
    updateSuccessCallback() {
      this.$message.success({
        message: '编辑成功！',
        duration: '2000'
      })
      this.getList() // 请求数据
    },
    /**
     * @description: 编辑 只有公有云可编辑
     * @param {*} row
     * @return {*}
     */
    editClick(row) {
      this.updateInfo = JSON.parse(JSON.stringify(row))
      this.showUpdateDialog = true // 展示
    },
    /**
     * @description: 创建 回调
     * @return {*}
     */
    createSuccessCallback() {
      this.$message.success({
        message: '创建镜像成功！',
        duration: '2000'
      })
      this.pageNum = 1
      this.getList() // 请求数据
    },
    /**
     * @description: 创建
     * @return {*}
     */
    createClick() {
      this.showCreateDialog = true
    },
    /**
     * @description: 当前行是否公有云
     * @param {*} row
     * @return {*}
     */
    isRowCloudPublic(row) {
      return isCloudPublic(row.cloudProvider)
    },
    /**
     * @description: 同步
     * @return {*}
     */
    syncClick() {
      this.syncLoading = true
      syncInstanceType({})
        .then((res) => {
          this.$message.success({
            message: '同步成功！',
            duration: '2000'
          })
          this.pageNum = 1 // 第一页
          this.getList() // 刷新数据
        })
        .finally(() => {
          this.syncLoading = false
        })
    },
    /**
     * @description: 选择
     * @param {*} selection
     * @return {*}
     */
    handleSelectionChange(selection) {
      this.selection = selection
    },
    /**
     * @description: 批量删除
     * @return {*}
     */
    batchDeleteClick() {
      if (this.selection.length === 0) {
        this.$message.warning('请先选择资源规格')
        return
      }
      const ids = []
      for (const item of this.selection) {
        ids.push(item.id)
      }
      this.$confirm('是否确认批量删除当前已选中的资源规格？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        this.btnLoadingBatchDel = true
        deleteInstanceType({ ids })
          .then((res) => {
            this.selection = []
            this.$message.success('批量删除成功')
            if (this.list.length === 1) {
              // 当前页只有一条数据时 删除完刷新上一页数据
              this.pageNum = Math.max(this.pageNum - 1, 1)
            }
            this.getList() // 请求数据
          })
          .finally(() => {
            this.btnLoadingBatchDel = false
          })
      })
    },
    /**
     * @description: 删除取消
     * @param {*} index
     * @return {*}
     */
    deleteCancel(index) {
      this.$refs[`popover-delete-${index}`][0].doClose() // 取消popover
    },
    /**
     * @description: 删除
     * @param {*} row
     * @param {*} index
     * @return {*}
     */
    deleteClick(row, index) {
      deleteInstanceType({
        ids: [row.id]
      }).then((res) => {
        this.$refs[`popover-delete-${index}`][0].doClose() // 取消popover
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          // 当前页只有一条数据时 删除完刷新上一页数据
          this.pageNum = Math.max(this.pageNum - 1, 1)
        }
        this.getList() // 请求数据
      })
    },
    /**
     * @description: 获取列表
     * @return {*}
     */
    getList() {
      this.handleRequestAndResp(getInstanceTypeList, {
        criteria: this.criteria,
        keyword: this.searchKey,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.container {
  .list-item {
    background: #ffffff;
    box-shadow: 0px 0px 5px 0px rgba(217, 213, 234, 0.5);
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;

    .top {
      margin-bottom: 10px;
    }

    .name {
      .textStyle(16px, 600, #262626);
      line-height: 24px;
    }

    .divider {
      margin-bottom: 15px;
      height: 1px;
      background: #f2f2f2;
    }

    .block {
      margin-bottom: 20px;
      background: #ffffff;
      border-radius: 1px;
      border: 1px solid #ececec;
      &:last-child {
        margin-bottom: 0;
      }

      .title {
        background: #fdfdfd;
        border-bottom: 1px solid #ececec;
        height: 36px;
        line-height: 36px;
        .textStyle(14px, 500, #262626);
        padding-left: 20px;
      }

      .row {
        display: flex;
        align-items: center;
        padding: 15px 20px;

        .row-item {
          flex: 1;
          .key {
            display: inline-block;
            margin-right: 12px;
            .textStyle(14px, 400, #C3C3C3);
            line-height: 20px;
          }
          .val {
            display: inline-block;
            .textStyle(14px, 500, #4a4a4a);
            line-height: 20px;
          }
        }
      }
    }
  }
}
</style>
